package com.workcell.workdata.im.component.observer;

import com.workcell.workdata.im.component.event.SubscriberEvent;
import com.workcell.workdata.im.feign.IMicroWebhookService;
import com.workcell.workdata.im.model.message.MicroEvent;
import com.workcell.workdata.im.repository.MicroServerRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.net.URI;

@Component
public class MicroWebhookObserver implements ApplicationListener<SubscriberEvent> {

    @Resource
    private IMicroWebhookService webhookService;

    @Resource
    private MicroServerRepository microServerRepository;

    @Override
    @Async("feignTaskExecutor")
    public void onApplicationEvent(SubscriberEvent event) {

        String webhook = microServerRepository.getWebhook(event.getServerId());

        if (StringUtils.isBlank(webhook)) {
            return;
        }

        MicroEvent hookEvent = new MicroEvent();
        hookEvent.setUid(event.getUid());
        hookEvent.setAction(event.getAction());
        webhookService.notify(URI.create(webhook),hookEvent);
    }

}
